﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Sql;
using Microsoft.Win32;

namespace CDMS
{
    public partial class frmLoadServer : Form
    {
        string name = "";

        public string SName
        {
            get { return name; }
            set { name = value; }
        }

        public frmLoadServer()
        {
            InitializeComponent();
            btn_OK.Enabled = false;
            BackgroundWorker bgJ = new BackgroundWorker();
            bgJ.DoWork += new DoWorkEventHandler(bgJ_DoWork);
            bgJ.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgJ_RunWorkerCompleted);
            bgJ.RunWorkerAsync();

            FormGlobals.ShowWaitForm();
        }
        void bgJ_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                loadServer();

                e.Result = true;
            }
            catch (Exception)
            {
                e.Result = false;
            }

        }

        void bgJ_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            FormGlobals.CloseWaitForm();
            if (dgvList.Rows.Count > 0)
                btn_OK.Enabled = true;
        }

        void loadServer()
        {
            SqlDataSourceEnumerator servers = SqlDataSourceEnumerator.Instance;
            DataTable serversTable = new DataTable();
            serversTable = servers.GetDataSources();

            int i = dgvList.Rows.Count;

            if (serversTable.Rows.Count > 0) //chỉ xuất hiện khi máy không kết nối mạng
            {
                string serverName = "";
                string instanceName = "";
                foreach (DataRow row in serversTable.Rows)
                {
                    // Add this to your list
                    serverName = row["ServerName"].ToString();
                    instanceName = row["InstanceName"].ToString();

                    dgvList.Rows.Insert(i, 1);
                    if (instanceName.Trim().Length > 0)
                        dgvList.Rows[i].Cells["ServerName"].Value = (string.Format("{0}\\{1}", serverName, instanceName));
                    else
                        dgvList.Rows[i].Cells["ServerName"].Value = string.Format("{0}", serverName);

                    i++;
                }
            }
            else //Khi máy không kết nối mạng thì chỉ lấy ra trên máy này
            {
                RegistryKey localMachine;
                try
                {
                    localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
                }
                catch
                {
                    localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                }
                var rk = localMachine.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server");
                var instances = (String[])rk.GetValue("InstalledInstances");

                if (instances.Length > 0)
                {
                    string serverName = "";
                    string instanceName = "";

                    foreach (String element in instances)
                    {
                        // Add this to your list
                        serverName = System.Environment.MachineName;
                        instanceName = element;
                        dgvList.Rows.Insert(i, 1);
                        if (instanceName == "MSSQLSERVER")
                            dgvList.Rows[i].Cells["ServerName"].Value = string.Format("{0}", serverName);
                        else
                            dgvList.Rows[i].Cells["ServerName"].Value = (string.Format("{0}\\{1}", serverName, instanceName));

                        i++;
                    }

                }

            }

        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                name = dgvList.SelectedRows[0].Cells["ServerName"].Value.ToString();
                DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();

        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            btn_OK_Click(null, null);
        }
    }
}
